#include <iostream>
#include <cmath>
#include <algorithm> 
#include "Hermite.hpp"
using namespace std;
// Hermite多项式求导
double HermiteDerivative(double* x, double* y, double* m, int n, double a) {
    const double epsilon = 1e-6; 
    double result1 = Hermite(x, y, m, n, a);
    double result2 = Hermite(x, y, m, n, a + epsilon);
    double derivative = (result2 - result1) / epsilon;
    return derivative;
}

int main() {
    // 数组初始化
    double* x = new double[5];
    double* y = new double[5];
    double* m = new double[5];

    double init_x[] = {0, 3, 5, 8, 13};
    copy(init_x, init_x + 5, x);

    double init_y[] = {0, 225, 383, 623, 993};
    copy(init_y, init_y + 5, y);

    double init_m[] = {75, 77, 80, 74, 72};
    copy(init_m, init_m + 5, m);

    // 用以上数据计算Hermite插值多项式并返回a对应的result
    double p = Hermite(x, y, m, 5, 10);
    double v = HermiteDerivative(x, y, m, 5, 10);
    cout << "(a)" << endl;
    cout << "The position of the car for t=10 seconds: " << p << " feet" << endl;
    cout << "The speed of the car for t=10 seconds: " << v << " ft/s" << endl;

    double s = 0.0;
    double S = 100.0;
    int steps = 10000;
    double size = (S - s) / steps;
    double max = -INFINITY;
    double x_max = s;

    for (int i = 0; i <= steps; i++) {
        double a = s + i * size;
        double value = HermiteDerivative(x, y, m, 5, a);
        if (value > max) {
            max = value;
            x_max = a;
        }
    }

    cout << "(b)" << endl;
    if (max > 81) { // 速度限制为81 ft/s，对应55 mph
        cout << "The car will exceed the speed limit of 55 miles per hour." << endl;
    } else {
        cout << "The car will not exceed the speed limit of 55 miles per hour." << endl;
    }

    // 释放动态分配的内存
    delete[] x;
    delete[] y;
    delete[] m;

    return 0;
}